<?php
include_once("columnModelInputs.php");

function generaGridJS($meta){

$atributs = $meta->getAtributs();
$atributs = explode(" ,", $atributs);
$tipus = $meta->getTipus();
$tipus = explode(" ,", $tipus);

$taula = $meta->getTaula();
$pk = $meta->getPk();
$idiomes = $meta->getNumIdiomes();

$variable = "
Ext.ns('Application');

//INICIO CLASE
".$taula."Grid = Ext.extend(Ext.grid.EditorGridPanel, {

     border:false
    ,initComponent:function() {
		//WINDOW
		this.Window = new ".$taula."FormWindow();
		this.Window.grid = this;
		
		//DATA STORE
		this.DataStore = new Ext.data.Store({
		    id: 'DataStore',
		    proxy: new Ext.data.HttpProxy({
		        url: 'php/".$taula."Grid.php',
		        method: 'POST'
		    }),
			remoteSort: true,
			baseParams:{task: 'LIST'},
			reader: new Ext.data.JsonReader({
		        root: 'results',
		        totalProperty: 'total',
		        id: 'id'
		    },[
";
			for( $i=0; $i<count($atributs); $i++ ){
				switch ( $tipus[$i] ){
					case 'string':
						$variable .= "\t\t\t{name: '$atributs[$i]', type: 'string'},\n";
					break;
					case 'blob':
						$variable .= "\t\t\t{name: '$atributs[$i]', type: 'string'},\n";
					break;
					case 'time':
						$variable .= "\t\t\t{name: '$atributs[$i]', type: 'string'},\n";
					break;
					case 'date':
						$variable .= "\t\t\t{name: '$atributs[$i]', type: 'date', dateFormat: 'd/m/Y'},\n";
					break;
					case 'int':
						$variable .= "\t\t\t{name: '$atributs[$i]', type: 'int'},\n";
					break;
					case 'real':
						$variable .= "\t\t\t{name: '$atributs[$i]', type: 'float'},\n";
					break;
					default:
					break;
				}
			}
			$variable = substr ($variable, 0, -2); //eliminem ,\n de l'ultim camp
$variable .= "
			]),
				sortInfo:{field: '$pk', direction: 'DESC'}
		});
		
		//COLUMN MODEL
		this.ColumnModel = new Ext.grid.ColumnModel(
	    [{
";
			for( $i=0; $i<count($atributs); $i++ ){
				//PK o ID2 o IDIOMA
				if( $atributs[$i] == $pk or $atributs[$i] == "id2" or $atributs[$i] == "idioma" ){
					switch ( $atributs[$i] ){
						case 'id2':
							$variable .= generaColumnNumberFieldNoEdit( "$atributs[$i]", "$atributs[$i]", 60, 1, 0);
						break;
						case 'idioma':
							$variable .= generaColumnNumberFieldNoEdit( "$atributs[$i]", "$atributs[$i]", 60, 0, 0);
						break;
						default:
							$variable .= generaColumnNumberFieldNoEdit( "$atributs[$i]", "$atributs[$i]", 60, 0, 1);
						break;
					}
				//ALTRES
				}else{
					switch ( $tipus[$i] ){
						case 'string':
							if( substr ($atributs[$i], 0, 4) == "img_" ){
								$variable .= generaColumnImgField( "$atributs[$i]", "$atributs[$i]", 150, 0);
							}else{
								if( substr ($atributs[$i], 0, 5) == "file_" ){
									$variable .= generaColumnTextFieldNoEdit( "$atributs[$i]", "$atributs[$i]", 150, 0);
								}else{
									$variable .= generaColumnTextField( "$atributs[$i]", "$atributs[$i]", 150, "Number.MAX_VALUE", 1, 0);
								}
							}
						break;
						case 'blob':
							$variable .= generaColumnTextFieldNoEdit( "$atributs[$i]", "$atributs[$i]", 150, 0);
						break;
						case 'time':
							$variable .= generaColumnTimeField( "$atributs[$i]", "$atributs[$i]", 100, "H:i", 30, 1, 0 );
						break;
						case 'date':
							$variable .= generaColumnDateField( "$atributs[$i]", "$atributs[$i]", 100, 'd/m/Y', 1, 0);
						break;
						case 'int':
							$variable .= generaColumnNumberField( "$atributs[$i]", "$atributs[$i]", 60, "Number.MAX_VALUE", 0, 1, 1, 0);
						break;
						case 'real':
							$variable .= generaColumnNumberField( "$atributs[$i]", "$atributs[$i]", 60, "Number.MAX_VALUE", 1, 1, 1, 0);
						break;
						default:
						break;
					}
				}
				$variable .= "\t},{";
			}
			$variable = substr ($variable, 0, -4); //eliminem \t},{ de l'ultim camp
$variable .= "
		}]
		);
		
		this.ColumnModel.defaultSortable = true;
		
		//GRID
		Ext.apply(this, {
			id: '".$taula."Grid',
			store: this.DataStore,
			cm: this.ColumnModel,
			enableColLock:false,
			//stripeRows: true,
			selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
			clicksToEdit:1,
			tbar: [{
				//text: 'Afegir',
				tooltip: TBAR_add,
				scope: this,
				iconCls:'add',
				handler: this.add
			}, '-', {
				// text: 'Editar',
				tooltip: TBAR_edit,
				scope: this,
				iconCls:'edit',
				handler: this.edit
			}, '-', {
				// text: 'Esborrar',
				tooltip: TBAR_remove,
				scope: this,
				iconCls:'remove',
				handler: this.removeConfirmation
			}, '-', {
				// text: 'Afegir Form',
				tooltip: TBAR_add_form,
				scope: this,
				iconCls:'add2',
				handler: this.add2
			},'-',{
				tooltip: TBAR_excel,
				scope: this,
				iconCls:'export',
				handler: this.excel
			},'-',{
				tooltip: TBAR_csv,
				scope: this,
				iconCls:'import',
				handler: this.csv
			}],
			bbar: new Ext.PagingToolbar({
				cls:'x-toolbar-bottom',
	            pageSize: 25,
	            store: this.DataStore,
				scope: this,
	            displayInfo: true,
	            displayMsg: '$taula {0} - {1} de {2}',
	            emptyMsg: BBAR_empty
			})
        });
		
		this.addListener('afteredit', this.update);
		this.addListener('rowdblclick', this.edit2); 		
				
       ".$taula."Grid.superclass.initComponent.apply(this, arguments);
    }
	
	,excel:function(){
		var taula = '$taula';
		window.open('php/generaExcel.php?taula='+taula, NOM_window_excel);
	}

	,csv:function(){
		var taula = '$taula';
		
		var csvFormulari = new Ext.FormPanel({
		bodyStyle: 'padding: 8px',
		url:'php/importarCSV.php',
		layout: 'form',
		labelWidth: 100,
		autoScroll: true,
		fileUpload: true,
		items: 
		[{
			xtype:'fileuploadfield',
			fieldLabel: 'csv',
			name: 'csv',
			width: 300,
			allowBlank: 0,
			//hideMode: 'offsets',
			buttonOnly: false,
			hideLabel: 0,
			hidden: 0
		}],
		buttonAlign: 'center',
		buttons: 
		[{
			text: BUTTON_cancel,
			handler: function(){
				csvWindow.hide();
			}
		/*},{
			text: BUTTON_reset,
			handler: function(){
				csvFormulari.getForm().reset();
			}*/
		},{
			text: BUTTON_save,
			scope: this,
			handler: function() {
				var store = this.store;
				if (csvFormulari.form.isValid()) {
					csvFormulari.form.submit({
						waitMsg: AJAX_wait,
						params:{
							taula: '$taula'
						},
						failure: function(form, action) {
							Ext.MessageBox.alert(NOM_window_alert, ERROR_bbdd);
						},
						success: function(form, action) {
							Ext.Msg.alert(NOM_window_alert, SUCCESS_add, function(btn, text){
								if (btn == 'ok'){
									store.reload();
									csvWindow.hide();
								}
							
							});
						}
					});
				}
				else {
					Ext.MessageBox.alert(NOM_window_alert, ERROR_obligatoris);
				}
			}	
		}]
	});
		
		var csvWindow = new Ext.Window({
			title: NOM_window_csv,
			width: 640,
			height: 480,
			layout: 'fit',
			closeAction: 'hide',
			items: [csvFormulari]
	    });
		
		csvWindow.show();
	}

	,update:function(oGrid_event){
		var store2 = this.store;
		
		Ext.Ajax.request({   
			waitMsg: AJAX_wait,
			url: 'php/".$taula."Grid.php',
			params: {
				task: 'UPDATE',
";
			for( $i=0; $i<count($atributs); $i++ ){
				switch ( $tipus[$i] ){
					case 'date':
						$variable .= "\t\t\t\t$atributs[$i]: oGrid_event.record.data.$atributs[$i].format('d/m/Y'),\n";
					break;
					default:
						$variable .= "\t\t\t\t$atributs[$i]: oGrid_event.record.data.$atributs[$i],\n";
					break;
				}
			}
			$variable = substr ($variable, 0, -2); //eliminem \n, de l'ultim camp
$variable .= "
			}, 
			success: function(response){							
				var result=eval(response.responseText);
				switch(result){
					case 1:
						store2.commitChanges();
					break;					
					default:
						Ext.MessageBox.alert(NOM_window_alert,ERROR_update);
					break;
				}
			},
			failure: function(response){
				var result=response.responseText;
				Ext.MessageBox.alert(NOM_window_alert,ERROR_bbdd);		
			}									    
		});   
	}
	
	,edit2:function(){
		var grid = this;
		var r = this.selModel.getSelected();
		var id2 = r.get('id2');
		this.Window.formulari.getForm().reset();
		this.Window.accio.setValue('UPDATE');
		this.Window.show();
		
		Ext.Ajax.request({   
			waitMsg: AJAX_wait,
			url: 'php/".$taula."Grid.php',
			params: {
				task: 'ID2',
				id2: id2
			}, 
			success: function(response){
				var result = Ext.util.JSON.decode(response.responseText);
";
				for( $i=0; $i<count($atributs); $i++ ){
					//PK o ID2 o IDIOMA
					if( $atributs[$i] == $pk or $atributs[$i] == "id2" or $atributs[$i] == "idioma" ){
						$variable .= "\t\t\t\tgrid.Window.$atributs[$i].setValue(r.get('$atributs[$i]'));\n";
					//IMG
					}else{
						//ALTRES
						if( substr ($atributs[$i], 0, 4) == "img_" or substr ($atributs[$i], 0, 5) == "file_" ){
							$variable .= "\t\t\t\tgrid.Window['$atributs[$i]'].setValue(result.results[0].$atributs[$i]);\n";
						}else{
							for( $j=1; $j<=$idiomes; $j++ ){
								$variable .= "\t\t\t\tgrid.Window['$atributs[$i]$j'].setValue(result.results[$j-1].$atributs[$i]);\n";
							}
						}
					}
				}

$variable .= "
				//grid.Window.show(); //si ho poso aqui, si primer edito i despres afegeixo no es resetejen els valors
			},
			failure: function(response){
				var result=response.responseText;
				Ext.MessageBox.alert(NOM_window_alert,ERROR_bbdd);	         
			} 
		});
	}
	
	,edit:function(){
		if(this.selModel.getCount() == 1){
				this.edit2();
		}else{
			Ext.MessageBox.alert(NOM_window_alert,ERROR_select_fila);
		}
	}
	
	,add2:function(){
		this.Window.formulari.getForm().reset();
		this.Window.accio.setValue('INSERT');
		
		this.Window.show();
	}
	
	,add:function(){
		var store2 = this.store;
		var sm2 = this.selModel;
		
		Ext.Ajax.request({   
			waitMsg: AJAX_wait,
			url: 'php/".$taula."Grid.php',
			params: {
				task: 'ADD'
			}, 
			success: function(response){              
				var result=eval(response.responseText);
				switch(result){
					case 1:
						store2.sort('$pk', 'DESC');
						store2.reload({callback: function(){ sm2.selectFirstRow(); }});
					break;
					default:
						Ext.MessageBox.alert(NOM_window_alert,ERROR_add);
					break;
				}        
			},
			failure: function(response){
				var result=response.responseText;
				Ext.MessageBox.alert(NOM_window_alert,ERROR_bbdd);	         
			} 
		});		
	}	
	
	,removeConfirmation:function(){
	    if(this.selModel.getCount() == 1){
			Ext.Msg.show({
				title:NOM_window_alert,
				msg: QUESTION_delete_fila,
				buttons: Ext.Msg.YESNO,
				fn: this.remove,
				scope: this,
				icon: Ext.MessageBox.QUESTION
			});
	    } else if(this.selModel.getCount() > 1){
			Ext.Msg.show({
				title:NOM_window_alert,
				msg: QUESTION_delete_files,
				buttons: Ext.Msg.YESNO,
				fn: this.remove,
				scope: this,
				icon: Ext.MessageBox.QUESTION
			});
	    } else {
			Ext.MessageBox.alert(NOM_window_alert,ERROR_select_fila);
	    }
	}

	,remove:function(btn){
	    if(btn=='yes'){
			var store2 = this.store;
	        var selections = this.selModel.getSelections();
	        var prez = [];
	        for(i = 0; i< this.selModel.getCount(); i++){
				prez.push(selections[i].json.id2);
	        }
	        var encoded_array = Ext.encode(prez);
			
	        Ext.Ajax.request({  
	            waitMsg: AJAX_wait,
	            url: 'php/".$taula."Grid.php', 
	            params: { 
					task: 'DELETE', 
					ids:  encoded_array
	            }, 
	            success: function(response){
					var result=eval(response.responseText);
					switch(result){
						case 1:
							store2.reload();
							//store2.reload({params:{ start:0, limit:25}});
						break;
						default:
							Ext.MessageBox.alert(NOM_window_alert,ERROR_remove);
						break;
					}
	            },
	            failure: function(response){
					var result=response.responseText;
					Ext.MessageBox.alert(NOM_window_alert,ERROR_bbdd);     
	            }
	        });
	    }  
	}
 
    ,onRender:function() {
		this.store.load({params:{start:0, limit:25}});
		".$taula."Grid.superclass.onRender.apply(this, arguments);
    }
	
});
 
Ext.reg('".$taula."Grid', ".$taula."Grid);
//FIN CLASE
";

return $variable;
}


?>